import { getLayoutProps } from "@/common/layout/getProps";
import { ProForm } from "@/components/ProForm";
import type { Dayjs } from "dayjs";
import dayjs from "dayjs";
import { cloneDeep } from "lodash";
import { PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Col,
  Select,
  DatePicker,
  Button,
  Form,
  Input,
  message,
  Modal,
  Row,
  Space,
  Table,
  Pagination,
  type TableColumnsType
} from "antd";
import { useState,useEffect } from "react";
import styles from "./index.module.scss";
import { http } from "@/utils/request";

type TableDataType = {
  id: string;
  field1: string;
  field2: string;
  field3: string;
  field4: string;
  field5: string;
  field6: string;
  field7: string;
  field8: string;
  field9: string | Dayjs;
  field10: string;
  field11: string;
  field12: string;
  field13: string;
  field14: string;
  pmRewardsApplyPersonQueries: any[];
}

const SpecialAwards = () => {
  const [form] = Form.useForm()
  const [list, setList] = useState([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({
    itemName:'',
    applyPersonName:'张三',
    date:'',
    deptName:'财务部门',
    projectContent:'',
    completionStatus:'',
    recognitionStatus:'',
    reviewExplanation:'',
    pmRewardsApplyPersonQueries: [{rewarderPersonId:'',rewarderPersonName:'',applicationBonus:'',reviewBonus:0}]
  });
  const [open, setOpen] = useState<boolean>(false);
  const [modelStatus,setModelStatus] = useState('');
  const [userOption,setUserOption] = useState([]);
  const [id,setId] = useState(null);

  const columns: TableColumnsType = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "单据编号",
      dataIndex: "code"
    },
    {
      align: "center",
      title: "申请人",
      width: 80,
      dataIndex: "applyPersonName"
    },
    {
      align: "center",
      title: "部门名称",
      width: 100,
      dataIndex: "deptName"
    },
    {
      align: "center",
      title: "嘉奖单名称",
      dataIndex: "itemName"
    },
    {
      align: "center",
      title: "嘉奖人数",
      dataIndex: "personCount"
    },
    {
      align: "center",
      title: "嘉奖总奖金",
      dataIndex: "applicationBonusTotal"
    },
    {
      align: "center",
      title: "嘉奖单说明",
      dataIndex: "projectContent"
    },
    {
      align: "center",
      title: "工作完成情况",
      dataIndex: "completionStatus"
    },
    {
      align: "center",
      title: "嘉奖周期",
      dataIndex: "date"
    },
    {
      align: "center",
      title: "表彰情况",
      dataIndex: "recognitionStatus"
    },
    {
      align: "center",
      title: "复核奖金",
      dataIndex: "reviewBonusTotal"
    },
    {
      align: "center",
      title: "复核情况说明",
      dataIndex: "reviewExplanation"
    },
    {
      align: "center",
      fixed:"right",
      title: "申请日期",
      dataIndex: "applyDate"
    },
    {
      align: "center",
      fixed:"right",
      title: "状态",
      dataIndex: "auditStatus",
      render: (_, record) => {
        return (
          <>
            {record.auditStatus === "0" && <span>待提交</span>}
            {record.auditStatus === "1" && <span>审核中</span>}
            {record.auditStatus === "2" && <span>已完成</span>}
            {record.auditStatus === "3" && <span>已驳回</span>}
          </>
          )
        }
    },
    {
      align: "center",
      fixed:"right",
      title: "操作",
      width: 180,
      render: (_, record) => {
        return (
          <>
            {record.auditStatus === "0" && 
              <Button type={'link'} onClick={() => {
                setModelStatus('edit');
                if (!record.pmRewardsApplyPersonQueries) {
                  record.pmRewardsApplyPersonQueries = [];
                }
                const data = cloneDeep(currentEdit);
                Object.keys(data).forEach(key => {
                  if (record.hasOwnProperty(key)) {
                    data[key] = record[key];
                  }
                });
                getDetail(record.id).then(result => {
                  data.pmRewardsApplyPersonQueries = result; // 这里的 result 是 Promise 解决后的值，应该是一个数组
                }).catch(error => {
                  console.error('Error:', error);
                });
                data.date = dayjs(data.date, 'YYYY-MM');
                getUserOption();
                setCurrentEdit(data);
                setOpen(true);
                setId(record.id);
              }}>编辑</Button>
            }
            <Button type={'link'} onClick={() => {
              setModelStatus('detail');
              if (!record.pmRewardsApplyPersonQueries) {
                record.pmRewardsApplyPersonQueries = [];
              }
              const data = cloneDeep(currentEdit);
              Object.keys(data).forEach(key => {
                if (record.hasOwnProperty(key)) {
                  data[key] = record[key];
                }
              });
              getDetail(record.id).then(result => {
                data.pmRewardsApplyPersonQueries = result; // 这里的 result 是 Promise 解决后的值，应该是一个数组
              }).catch(error => {
                console.error('Error:', error);
              });
              data.date = dayjs(data.date, 'YYYY-MM');
              getUserOption();
              setCurrentEdit(data);
              setOpen(true);
            }}>详情</Button>
          </>
        )
      }
    }
  ]
  const handleOk = () => {
    const { pmRewardsApplyPersonQueries, ...pmRewardsApplyQuery } = currentEdit;
    const infoIsEmpty = Object.values(pmRewardsApplyQuery).some(value=>value=='');
    const rewardsEmpty = pmRewardsApplyPersonQueries.some(item => !item.rewarderPersonId || !item.applicationBonus);
    if(infoIsEmpty||rewardsEmpty){
      message.error('请填写所有申请单项');
    }else{
      const formData = {
        pmRewardsApplyQuery:{...pmRewardsApplyQuery,status:'11'},
        pmRewardsApplyPersonQueries:pmRewardsApplyPersonQueries
      }
      formData.pmRewardsApplyQuery.date = dayjs(formData.pmRewardsApplyQuery.date).format('YYYY-MM-DD');
      if(modelStatus=='add'){
        addSave(formData)
      }
      if(modelStatus=='edit'){
        editSave(formData)
      }
    }
  }
  //新增接口
  const addSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmRewardsApply/add',
        data:{...formData},
      })
      if(res.code == 200){
        message.success('专项嘉奖新增成功!');
        setOpen(false);
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(formData:object) =>{
    formData.pmRewardsApplyQuery.id = id
    try {
      const res = await http.put({
        url:'/PmRewardsApply/update',
        data:{...formData},
      })
      if(res.code == 200){
        message.success('专项嘉奖修改成功!');
        setOpen(false);
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }

  const handleCancel = () => {
    setOpen(false);
  }
  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }
  const getUserOption = async()=>{
    try {
      // const res = await http.post({
      //   url:'/BaseUser/qryDropDownOptions',
      //   data:{"bizUnitId":"0001101000000000182V"}
      // })
      const res = await http.post({
        url:'/BaseUser/qryStaffBaseUserByOrgId',
        data:{bizUnitId:'0001101000000000182V'}
      })
      setUserOption(res.rows.map(item=>({value:item.staffId,label:item.name +'-'+item.staffNo,name:item.name})));
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //查询接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/PmRewardsApply/qryList',
        params:{
          code:form.getFieldValue('code'),
          deptId:form.getFieldValue('deptId'),
          itemName:form.getFieldValue('itemName'),
          pageNum:pageNum,
          pageSize:pageSize,
        }
      })
      setList(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //详情接口
  const getDetail = async(id:number)=>{
    try {
      const res = await http.get({
        url:'/PmRewardsApplyPerson/qryList',
        params:{rewarderId:id}
      })
      if(res.code == 200){
        const data = cloneDeep(res.data);
        return data
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  useEffect(()=>{
    getList();
  },[pageNum,pageSize])
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'} onSearch={getList} onReset={getList}>
        <Form.Item
          label={'单据编号'}
          name="code"
        >
          <Input placeholder={'请输入'}></Input>
        </Form.Item>
        <Form.Item
          label={'嘉奖单名称'}
          name="itemName"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          label={'部门名称'}
          name="deptId"
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </ProForm>

      <Row className={'mb-[20px]'}>
        <Space>
          <Button type={'primary'} icon={<PlusOutlined />} onClick={() => {
            setModelStatus('add');
            setCurrentEdit({
              itemName:'',
              applyPersonName:'张三',
              date:'',
              deptName:'财务部门',
              projectContent:'',
              completionStatus:'',
              recognitionStatus:'',
              reviewExplanation:'',
              pmRewardsApplyPersonQueries: [{rewarderPersonId:'',rewarderPersonName:'',applicationBonus:'',reviewBonus:0}]
            });
            getUserOption();
            setOpen(true);
            setId(null);
          }}>申请</Button>
        </Space>
      </Row>

      <Table
        scroll={{ x: 1800 }}
        dataSource={list}
        columns={columns}
        rowKey={(record) => `${record.id}`}
        pagination={false}
      ></Table>
      <Pagination
        className={'m-[20px] text-end'}
        current={pageNum}
        pageSize={pageSize}
        total={total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={changePagination}
      />

      <Modal
        className={styles.modal}
        width={'70%'}
        open={open}
        title={
          <div className={'w-full text-center'}>嘉奖申请单</div>
        }
        afterClose={() => {
          setCurrentEdit({
            itemName:'',
            applyPersonName:'张三',
            date:'',
            deptName:'财务部门',
            projectContent:'',
            completionStatus:'',
            recognitionStatus:'',
            reviewExplanation:'',
            pmRewardsApplyPersonQueries: [{rewarderPersonId:'',rewarderPersonName:'',applicationBonus:'',reviewBonus:0}]
          });
        }}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={'提交'}
        cancelText={'取消'}
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <Button type={'primary'} onClick={() => {
              const { pmRewardsApplyPersonQueries, ...pmRewardsApplyQuery } = currentEdit;
              const infoIsEmpty = Object.values(pmRewardsApplyQuery).some(value=>value=='');
              const rewardsEmpty = pmRewardsApplyPersonQueries.some(item => !item.rewarderPersonId || !item.applicationBonus);
              if(infoIsEmpty||rewardsEmpty){
                message.error('请填写所有申请单项');
              }else{
                const formData = {
                  pmRewardsApplyQuery:{...pmRewardsApplyQuery,status:"10"},
                  pmRewardsApplyPersonQueries:pmRewardsApplyPersonQueries
                }
                formData.pmRewardsApplyQuery.date = dayjs(formData.pmRewardsApplyQuery.date).format('YYYY-MM-DD');
                if(modelStatus=='add'){
                  addSave(formData)
                }
                if(modelStatus=='edit'){
                  editSave(formData)
                }
              }
            }}>保存</Button>
            <OkBtn />
          </>
        )}
      >
        <div className={[styles.desc, 'mr-[40px]'].join(' ')}>
          <Row>
            <Col className={"label"} span={4}>
              嘉奖单申请名称
            </Col>
            <Col className={"content"} span={20}>
              <Input placeholder={'请输入'} value={currentEdit.itemName} onChange={e => {
                    currentEdit.itemName = e.target.value;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }}/>
            </Col>
          </Row>
          <Row>
            <Col className={"label"} span={4}>申请人</Col>
            <Col className={"content"} span={4}>{currentEdit.applyPersonName}</Col>
            <Col className={"label"} span={4}>嘉奖期间</Col>
            <Col className={"content"} span={4}><DatePicker value={currentEdit.date} onChange={e => {
                    currentEdit.date = e;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }}/></Col>
            <Col className={"label"} span={4}>部门名称</Col>
            <Col className={"content"} span={4}>{currentEdit.deptName}</Col>
          </Row>
          {
            currentEdit.pmRewardsApplyPersonQueries!.map((item, index) => {
              return (
                <Row className={'dynamic-row'} key={index}>
                  <Col className={"label"} span={4}>嘉奖人</Col>
                  <Col className={"content"} span={4}>
                    <Select
                      placeholder={'请选择'}
                      value={item.rewarderPersonId}
                      onChange={(e,option) => {
                        item.rewarderPersonId = e;
                        currentEdit.pmRewardsApplyPersonQueries[index].rewarderPersonName = option.name
                        setCurrentEdit(cloneDeep(currentEdit))
                      }}
                      showSearch
                      filterOption={(input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                      }
                      options={userOption}
                    />
                  </Col>
                  <Col className={"label"} span={4}>申请奖金</Col>
                  <Col className={"content"} span={4}><Input placeholder={'请输入'} value={item.applicationBonus} onChange={e => {
                    item.applicationBonus = e.target.value;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }} /></Col>
                  <Col className={"label"} span={4}>复核奖金</Col>
                  <Col className={"content"} span={4}><Input placeholder={'请输入'} disabled={
                    modelStatus=='add'
                  } value={item.reviewBonus} onChange={e => {
                    item.reviewBonus = e.target.value;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }} /></Col>
                  {
                    index !== 0 ?
                    <Button className={'rm-btn'} type={'link'} danger size={'small'} onClick={() => {
                      currentEdit.pmRewardsApplyPersonQueries?.splice(index, 1);
                      setCurrentEdit(cloneDeep(currentEdit));
                    }}>删除</Button>
                      : null
                  }
                </Row>
              )
            })
          }
          <Row justify={'center'} className={'px-[16px] py-[12px]'}>
            <Button type={'link'} icon={<PlusOutlined />} onClick={() => {
              setCurrentEdit({
                ...currentEdit,
                pmRewardsApplyPersonQueries: currentEdit.pmRewardsApplyPersonQueries?.concat({
                  rewarderPersonId: "",
                  applicationBonus: "",
                  reviewBonus: 0
                })
              })
            }}>添加嘉奖人</Button>
          </Row>
          <Row>
            <Col className={"label"} span={4}>
              <span>嘉奖申请说明</span>
            </Col>
            <Col className={"content"} span={20}>
              <Input.TextArea rows={3} placeholder={'请输入'} value={currentEdit.projectContent} onChange={e => {
                    currentEdit.projectContent = e.target.value;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }}/>
            </Col>
          </Row>
          <Row>
            <Col className={"label"} span={4}>
              <span>工作完成情况</span>
            </Col>
            <Col className={"content"} span={20}>
              <Input.TextArea rows={3} placeholder={'请输入'} value={currentEdit.completionStatus} onChange={e => {
                    currentEdit.completionStatus = e.target.value;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }}/>
            </Col>
          </Row>
          <Row>
            <Col className={"label"} span={4}>
              <span>表彰情况</span>
            </Col>
            <Col className={"content"} span={20}>
              <Input.TextArea rows={3} placeholder={'请输入'} value={currentEdit.recognitionStatus} onChange={e => {
                    currentEdit.recognitionStatus = e.target.value;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }}/>
            </Col>
          </Row>
          <Row>
            <Col className={"label"} span={4}>
              <span>复核情况说明</span>
            </Col>
            <Col className={"content"} span={20}>
              <Input.TextArea rows={3} placeholder={'请输入'} value={currentEdit.reviewExplanation} onChange={e => {
                    currentEdit.reviewExplanation = e.target.value;
                    setCurrentEdit(cloneDeep(currentEdit));
                  }}/>
            </Col>
          </Row>
        </div>
      </Modal>
    </PageContainer>
  )
}

export const getServerSideProps = getLayoutProps;
export default SpecialAwards;
